<script setup lang="ts">
// 导入必要的模块和工具函数
import { computed, ref, watch } from "vue";
import { useForm, useFormRules } from "@/hooks/common/form";
import { $t } from "@/locales";
import type {
  ApiSysEmailSendConfigInput,
  ApiSysEmailSendConfigOut,
  ApiUserInput,
  ApiUserOut,
} from "@/api-services";
import { UserApi } from "@/api-services/apis/user-api";
import { feature, getAPI } from "@/axios-utils";
import { queryDone } from "@/utils/api";
import { REG_PWD, REG_USER_NAME } from "@/constants/reg";
import { ApiroleserviceApi } from "@/api-services/apis/apiroleservice-api";
import { SysemailsendconfigApi } from "@/api-services/apis/sysemailsendconfig-api";

// 定义组件名称
defineOptions({
  name: "EmailConfigOperateModal",
});

// 定义组件props
interface Props {
  /** the type of operation */
  operateType: UI.TableOperateType;
  /** the edit row data */
  rowData?: ApiSysEmailSendConfigOut | null;
}

const props = defineProps<Props>();

// 定义组件事件
interface Emits {
  (e: "submitted"): void;
}

const emit = defineEmits<Emits>();

// 定义visible模型，用于控制抽屉的显示隐藏
const visible = defineModel<boolean>("visible", {
  default: false,
});

// 表单相关钩子和变量
const { formRef, validate, restoreValidation} = useForm();
const { defaultRequiredRule } = useFormRules();

// 根据操作类型计算标题
const title = computed(() => {
  const titles: Record<UI.TableOperateType, string> = {
    add: "添加邮件配置",
    edit: "编辑邮件配置",
  };
  return titles[props.operateType];
});

// 定义表单数据模型类型，基于ApiSysEmailSendConfigInput接口
type Model = {
  [K in keyof Pick<
    ApiSysEmailSendConfigInput,
    | "id"
    | "emailSmtpHost"
    | "emailSmtpPort"
    | "emailAccount"
    | "emailIsHtml"
    | "emailPassword"
    | "emailDisplayName"
    | "emailIsSsl"
    | "isEnable"
    | "isDefault"
    | "remark"
    | "sendMode"
    | "options"
  >]: NonNullable<ApiSysEmailSendConfigInput[K]>;
};

// 表单数据模型
const model = ref(createDefaultModel());

// 创建默认表单数据模型函数
function createDefaultModel(): Model {
  return {
    id: 0,
    emailSmtpHost: "",
    emailSmtpPort: "",
    emailAccount: "",
    emailPassword: "",
    emailIsHtml: false,
    emailDisplayName: "",
    emailIsSsl: false,
    isEnable: true,
    isDefault: false,
    remark: "",
    sendMode: 0,
    options: "",
  };
}

// 初始化表单数据模型
function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === "edit" && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

// 关闭抽屉
function closeWindow() {
  visible.value = false;
}

// 提交表单处理函数
async function handleSubmit() {
  await validate();

  if (props.operateType === "add") {
    const [err, res] = await feature(
      getAPI(SysemailsendconfigApi).insert(model.value),
    );

    queryDone(err, async () => {
      if (res?.data.data) {
        window.$message?.success($t("common.addSuccess"));
        closeWindow();
        emit("submitted");
      }
    });
  } else {
    const [err, res] = await feature(
      getAPI(SysemailsendconfigApi).update(model.value),
    );

    queryDone(err, async () => {
      if (res?.data.data) {
        window.$message?.success($t("common.updateSuccess"));
        closeWindow();
        emit("submitted");
      }
    });
  }
}

// 表单验证规则
type RuleKey = Extract<
  keyof Model,
  "emailSmtpHost" | "emailSmtpPort" | "emailAccount" | "sendMode"
>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  emailSmtpHost: defaultRequiredRule,
  emailSmtpPort: defaultRequiredRule,
  emailAccount: defaultRequiredRule,
  sendMode: defaultRequiredRule,
};

// 安全套接字选项
const secureSocketOptions = computed(() => {
  const options = {
    None: "0",
    Auto: "1",
    SslOnConnect: "2",
    StartTls: "3",
    StartTlsWhenAvailable: "4",
  };
  return Object.entries(options).map(([key, value]) => ({
    label: key,
    value: value,
  }));
});

// 监听visible变化并初始化表单
watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    // getRoleOptions();
  }
});
</script>

<template>
  <!-- 邮件配置操作抽屉 -->
  <NModal v-model:open="visible" :title="title"  width="800px">
    <ElSpace direction="vertical">
      <!-- 表单区域 -->
      <ElForm ref="formRef"  :model="model" :rules="rules" label-width="auto">
        <ElRow :gutter="16" wrap>
          <!-- 表单字段 -->
          <ElCol :lg="12" :xs="24">
            <!-- SMTP服务器 -->
            <ElFormItem
              :label="$t('page.emailManage.emailConfig.emailSmtpHost')"
              name="emailSmtpHost"
            >
              <ElInput
                v-model="model.emailSmtpHost"
                :placeholder="
                  $t('page.emailManage.emailConfig.form.emailSmtpHost')
                "
              />
            </ElFormItem>
          </ElCol>
          <ElCol :lg="12" :xs="24">
            <!-- 邮件服务器Smtp端口 -->
            <ElFormItem
              :label="$t('page.emailManage.emailConfig.emailSmtpPort')"
              name="emailSmtpPort"
            >
              <ElInput
                v-model="model.emailSmtpPort"
                :placeholder="
                  $t('page.emailManage.emailConfig.form.emailSmtpHost')
                "
              />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="12" :xs="24">
            <!-- 邮箱账号 -->
            <ElFormItem
              :label="$t('page.emailManage.emailConfig.form.emailAccount')"
              name="emailAccount"
            >
              <ElInput
                v-model="model.emailAccount"
                :placeholder="
                  $t('page.emailManage.emailConfig.form.emailAccount')
                "
              />
            </ElFormItem>
          </ElCol>
          <ElCol :lg="12" :xs="24">
            <!-- 邮箱密码 -->
            <ElFormItem
              :label="$t('page.emailManage.emailConfig.emailPassword')"
              name="emailPassword"
            >
              <!-- 请输入密码/如果不修改密码，无需填写 -->
              <ElInput
                v-model="model.emailPassword"
                type="password"
                :placeholder="
                  props.operateType === 'add'
                    ? $t('page.emailManage.emailConfig.form.emailPassword')
                    : $t('page.emailManage.emailConfig.form.emailEmptyPassword')
                "
              />
            </ElFormItem>
          </ElCol>
          <ElCol :lg="12" :xs="24">
            <ElFormItem
              :label="$t('page.emailManage.emailConfig.emailDisplayName')"
              name="emailDisplayName"
            >
              <ElInput
                v-model="model.emailDisplayName"
                :placeholder="
                  $t('page.emailManage.emailConfig.form.emailDisplayName')
                "
              />
            </ElFormItem>
          </ElCol>
          <ElCol :lg="12" :xs="24">
            <!-- 安全选项 -->
            <ElFormItem
              :label="$t('page.emailManage.emailConfig.options')"
              name="options"
            >
              <ElSelect
                v-model="model.options"
                :placeholder="$t('page.emailManage.emailConfig.form.options')"
                :options="secureSocketOptions"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :lg="12" :xs="24">
            <ElFormItem
              :label="$t('page.emailManage.emailConfig.emailIsHtml')"
              name="emailIsHtml"
            >
              <ElSwitch v-model:model-value="model.emailIsHtml" />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="12" :xs="24">
            <ElFormItem
              :label="$t('page.manage.common.isEnable')"
              name="isEnable"
            >
              <ElSwitch v-model:model-value="model.isEnable" />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="12" :xs="24">
            <ElFormItem
              :label="$t('page.emailManage.emailConfig.isDefault')"
              name="isDefault"
            >
              <ElSwitch v-model:model-value="model.isDefault" />
            </ElFormItem>
          </ElCol>
          <ElCol :lg="12" :xs="24">
            <ElFormItem
              :label="$t('page.emailManage.emailConfig.emailIsSsl')"
              name="emailIsSsl"
            >
              <ElSwitch v-model:model-value="model.emailIsSsl" />
            </ElFormItem>
          </ElCol>

          <ElCol :lg="24" :xs="24">
            <ElFormItem

              :label="$t('page.manage.common.remark')"
              name="remark"
            >
              <ElInput type="textarea"
                v-model="model.remark"
                :auto-size="{ minRows: 2, maxRows: 5 }"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </ElForm>
    </ElSpace>
    <!-- 抽屉底部按钮 -->
    <template #footer>
      <ElSpace :size="16">
        <ElButton @click="closeWindow">{{ $t("common.cancel") }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{
          $t("common.confirm")
        }}</ElButton>
      </ElSpace>
    </template>
  </NModal>
</template>

<style scoped>
/* 组件样式：当前为空，可根据需要添加样式 */
</style>
